// index.tsx
import {Table, Pagination} from 'antd'
import React, {useState, useEffect} from 'react'
import {ArgTableProps, TableProps} from './type'
import styles from './index.less'

const useAsyncTable: React.FC<ArgTableProps> = (props: ArgTableProps) => {
	const {
		columns,
		total,
		pagination,
		params,
		callback,
		kid = 'projectNo',
		pageSizeOptionsKey,
		dataSource,
		loading,
		scroll,
		defaultCurrent,
		showRowSelection,
		defaultSelectedRowKeys,
		pageSizeOptions = [10, 20],
		selectCallback,
		getCheckboxProps,
		type = 'checkbox',
		bordered = true,
		clearSelection,
	} = props
	const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([])

	// 改变页码
	function handleTableChange(current: number, size: number) {
		if (callback) {
			callback({
				current,
				size,
			})
		}
	}
	// 清空选中数据
	useEffect(() => {
		if (clearSelection) {
			setSelectedRowKeys([])
		}
		if (defaultSelectedRowKeys) {
			setSelectedRowKeys(defaultSelectedRowKeys)
		}
	}, [dataSource])

	const onSelectChange = (
		newSelectedRowKeys: React.Key[],
		selectedRows: any[],
	) => {
		setSelectedRowKeys(newSelectedRowKeys)
		if (showRowSelection) {
			selectCallback?.(newSelectedRowKeys, selectedRows)
		}
	}

	const rowSelection = {
		selectedRowKeys,
		type,
		onChange: onSelectChange,
	}

	const data: TableProps = {
		rowKey: (record?: any) => (record ? record[kid] : ''),
		scroll: scroll || {x: 'max-content', y: 480},
		className: styles.table,
		columns,
		dataSource,
		loading,
	}
	if (showRowSelection) {
		data.rowSelection = getCheckboxProps
			? {...rowSelection, ...getCheckboxProps}
			: rowSelection
	}

	return (
		<>
			<Table {...data} bordered={bordered} pagination={false} />
			{pagination ? (
				<Pagination
					key={pageSizeOptionsKey}
					className={styles.pagination}
					defaultCurrent={defaultCurrent}
					current={Number(params.current)}
					total={total ? Number(total) : 0}
					showTotal={(totals: any, range: any) =>
						`第  ${range[0]} - ${range[1]} 条 / 总共 ${totals} 条`
					}
					showSizeChanger
					showQuickJumper
					pageSizeOptions={pageSizeOptions}
					// eslint-disable-next-line react/jsx-no-bind
					onChange={handleTableChange}
				/>
			) : null}
		</>
	)
}
export default useAsyncTable
